import { createSlice } from '@reduxjs/toolkit'
import { createAsyncThunk } from '@reduxjs/toolkit'
import { getSongDetail, getLyric } from '../service/player'
import type { PlayerDetailType, LyricType } from './type'


export const fetchPlayerDetailAction = createAsyncThunk(
  'getPlayerDetail',
  async (arg: { ids: number }, { dispatch }) => {
    await getSongDetail(arg.ids).then((res) => {
      console.log(res.songs[0],'获取歌曲详情')
      dispatch(changePlayerDetailAction(res.songs[0]))
      dispatch(changeCurrentSongIdAction(res.songs[0].id))
      console.log(res.songs[0].id,'获取歌曲id')
    })
  }
)

export const fetchLyricAction = createAsyncThunk(
  'getLyric',
  async (arg: { id: number }, { dispatch }) => {
    await getLyric(arg.id).then((res) => {
      console.log(res.lrc,'获取歌词')
      dispatch(changeLyricAction(res.lrc))
    })
  }
)

type playerState = {
  playerDetail: PlayerDetailType | null
  lyric: LyricType | null,
  currentSongId: number
}

const initialState: playerState = {
  playerDetail: null,
  lyric: null,
  currentSongId: 33894312

}

export const playerSlice = createSlice({
  name: 'player',
  initialState,
  reducers: {
    changePlayerDetailAction(state, action) {
      state.playerDetail = action.payload
    },
    changeLyricAction(state, action) {
      state.lyric = action.payload
    },
    changeCurrentSongIdAction(state, action) {
      state.currentSongId = action.payload
    }
  }
})

export const { changePlayerDetailAction, changeLyricAction, changeCurrentSongIdAction } =
  playerSlice.actions

export default playerSlice.reducer
